package cn.wolfcode.resolver;

import cn.wolfcode.annotation.UserParam;
import cn.wolfcode.cache.service.impl.UserInfoRedisServiceImpl;
import cn.wolfcode.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于解析请求映射里方法中声明的当前登录的用户的对象信息
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{

    @Autowired
    private UserInfoRedisServiceImpl userInfoRedisService;
    //表示当前解析器能解析哪些类型参数  true为支持指定类型  false表示不支持
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    //执行解析逻辑  前提必须是supportsParameter 返回true才执行
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取当前登录对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        //返回值就是把请求映射的方法声明形式参数之类的UserInfo对象的值   返回当前登录用户对象
        return userInfoRedisService.getUserByToken(token);
    }
}
